/**
 * 选择时间段组件
 */

import { useState } from 'react';
import { message, Space, Typography } from 'antd';
import TimeRangePickerModal from './TimeRangePickerModal';
import { useDeepCompareEffect } from 'ahooks';
import moment from 'moment';
import type { FC } from 'react';
import type { TPickerItem, TShowData } from './types';
import styles from './index.less';

const format = 'HH:mm';

/**
 * 日期选择组件
 * - left: 左侧偏移距离，以em为单位
 */
type TProps = {
  onChange?: TAnyFunction;
  value?: TShowData[];
  left?: number;
};

const CommonTimePeriodPicker: FC<TProps> = (props) => {
  const { onChange, value, left = 6 } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [data, setData] = useState<TPickerItem[]>([]);

  // 格式化成接口需要的时间格式
  const formatTime = (orgData: TPickerItem[]) =>
    orgData.map((obj) => {
      const [time1, time2] = obj.timeRange;
      return [time1.format(format), time2.format(format)];
    });

  // 格式化成组件需要的时间格式
  const getShowData = (orgData: TShowData[]): TPickerItem[] =>
    orgData.map((obj) => {
      const [time1, time2] = obj;
      return {
        timeRange: [moment(time1, format), moment(time2, format)],
      };
    });

  const handleSubmit = (val: TPickerItem[]) => {
    if (!(val && val.length)) {
      message.warn('至少设置一个时间段');
    } else {
      onChange && onChange(formatTime(val));
      setData(val);
      setVisible(false);
    }
  };

  useDeepCompareEffect(() => {
    if (value) {
      setData(getShowData(value));
    }
  }, [value]);

  const renderText = () => (
    <div className={styles.showWrap}>
      <div className={styles.showContent}>
        <Space direction="vertical">
          {data.map(({ timeRange }, idx) => (
            <Typography.Text key={idx}>
              <Typography.Text strong>时间段{idx + 1}</Typography.Text>：
              {timeRange[0].format(format)}~{timeRange[1].format(format)}
            </Typography.Text>
          ))}
        </Space>
      </div>
      <div className={styles.showBtn} onClick={() => setVisible(true)}>
        编辑
      </div>
    </div>
  );

  return (
    <div className={styles.pickerShowContainer} style={{ paddingLeft: `${left}em` }}>
      <div className={styles.pickerShowBox}>
        {data.length > 0 ? (
          renderText()
        ) : (
          <span
            className={styles.choseBtn}
            onClick={() => {
              setVisible(true);
            }}
          >
            点击选择
          </span>
        )}
      </div>

      {visible && (
        <TimeRangePickerModal
          visible={visible}
          data={data}
          onCancel={() => setVisible(false)}
          onSubmit={handleSubmit}
        />
      )}
    </div>
  );
};

export default CommonTimePeriodPicker;
